const request = require('../modules/request')

class Account {
    constructor() {
    }


    /**
     * 创建二维码ticket 会自动判断永久临时二维码 仅需要传入有效期 和 info
     * @param {*} expire_seconds 临时二维码请求说明 必填
     * @param {*} scene_info scene_id 或者 scene_str
     */
    async qrcodeCreate (expire_seconds = false, scene_info) {
        const access_token = await this.getAccessToken()
        if (!access_token) {
            return false
        }
        const uri = `https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=${access_token}`
        const scene = {}
        let action_name
        if (typeof scene_info == 'number') {
            scene['scene_id'] = scene_info
            action_name = expire_seconds? 'QR_SCENE':'QR_LIMIT_SCENE'
        } else {
            action_name = expire_seconds? 'QR_STR_SCENE':'QR_LIMIT_STR_SCENE'
            scene['scene_str'] = scene_info
        }

        const data = {
            action_name: action_name,
            action_info: {
                scene: scene
            }
        }
        // 临时二维码
        if (expire_seconds) {
            data['expire_seconds'] = expire_seconds
        }
        const res = await request.json(uri, data)
        return res
    }
    
    /**
     * 通过ticket换取二维码
     * https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
     * @param {*} ticket 
     */
    async showQRCode (ticket) {
        const uri = `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${ticket}`
        return uri
    }

    /**
     * 长链接转短链接接口
     * https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN
     * @param {*} long_url  需要转换的长链接，支持http://、https://、weixin://wxpay 格式的url
     * @param {*} action 此处填long2short，代表长链接转短链接 
     */
    async longToShort(long_url, action='long2short') {
        const access_token = await this.getAccessToken()
        if (!access_token) {
            return false
        }
        const uri = `https://api.weixin.qq.com/cgi-bin/shorturl?access_token=${access_token}`
        const data = {
            action: 'long2short',
            long_url: long_url
        }
       
        const res = await request.json(uri, data)
        return res
    }
}

module.exports = Account